#!/bin/bash
#
# $Id$
#

. $OPENARS_HOME/common/debug.h || exit 1
. $OPENARS_HOME/common/functions.h || exit 1

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME
[ -z "$1" ] && { ERR "need parameter \"filename\""; exit 1; }
[ ! -f "$1" ] && { ERR "not find file \"$1\""; exit 1; }

srvlist=`cat $1`
#srvlist=`get_hosts --control=YES`
INF "count hosts: `echo $srvlist | wc -w`"

OUTFILE=$OUTDIR/get_profile_info$(echo $(basename $1) | sed s/^srvlist// | sed s/txt//)out
:>$OUTFILE

put_file="$PRJDIR/get_profile_info.local.sh"
ssh_command="./get_profile_info.local.sh; rm ./get_profile_info.local.sh"

for host in $srvlist
do
    (
    sftp -o BatchMode=yes $user@$host &> /dev/null << END
put $put_file
END
    sftp_code=$?
    [ $sftp_code -ne 0 ] && { WARN "Error sftp-connect or sftp-commands on $host: exit_code=$sftp_code"; continue; }
    #server_info=`ssh $user@$host "$ssh_command"`
    SSH $user@$host "$ssh_command" server_info
        [ -z "$server_info" ] && continue
        #echo "$server_info" >> $OUTFILE
    	real_host=`echo "$server_info" | awk -F":" '/^HOST:/{print $2}'`
        os_version=`echo "$server_info" | awk -F":" '/^OS:/{print $2}'`
        ram=`echo "$server_info" | awk -F":" '/^RAM:/{print $2}'`
        cpu=`echo "$server_info" | awk -F":" '/^CPU:/{print $2}'`
        sn=`echo "$server_info" | awk -F":" '/^SN:/{print $2}'`
        server_model=`echo "$server_info" | awk -F":" '/^SERVER_MODEL:/{print $2}'`
        internal_hdd=`echo "$server_info" | awk -F":" '/^HDD:/{print $2}'`

        [ -z "$real_host" ] && ERR "not get REAL_HOST information from $host"
        [ -z "$os_version" ] && ERR "not get OS_VERSION information from $host"
        [ -z "$ram" ] && ERR "not get RAM information from $host"
        [ -z "$cpu" ] && ERR "not get CPU information from $host"
        [ -z "$sn" ] && ERR "not get SN information from $host"
        [ -z "$internal_hdd" ] && ERR "not get HDD information from $host"
        [ -z "$server_model" ] && ERR "not get SERVER_MODEL information from $host"

        echo ' <host>' > $TEMPDIR/$host.xout
        echo '  <hostname>'$host'</hostname>' >> $TEMPDIR/$host.xout
        echo '  <real_host>'$real_host'</real_host>' >> $TEMPDIR/$host.xout
        echo '  <os_version>'$os_version'</os_version>' >> $TEMPDIR/$host.xout
        echo '  <server_model>'$server_model'</server_model>' >> $TEMPDIR/$host.xout
        echo '  <cpu>'$cpu'</cpu>' >> $TEMPDIR/$host.xout
        echo '  <ip></ip>' >> $TEMPDIR/$host.xout
        echo '  <sn>'$sn'</sn>' >> $TEMPDIR/$host.xout
        echo '  <internal_hdd>'$internal_hdd'</internal_hdd>' >> $TEMPDIR/$host.xout
        echo '  <ram>'$ram'</ram>' >> $TEMPDIR/$host.xout
        echo ' </host>' >> $TEMPDIR/$host.xout

    ) &
done
WAIT 180

echo '<?xml version="1.0" encoding="UTF-8"?>' >> $OUTFILE
echo '<get_profile_info>' >> $OUTFILE
for ofile in `ls $TEMPDIR/*.xout`
do
    cat $ofile >> $OUTFILE
done
echo '</get_profile_info>' >> $OUTFILE
    
ECHO "$OUTFILE"

exit 0

